<template>
	<view class="upload_box">
		<view v-for="(item, index) in modelValue" :key="index" class="upload_box_item">
			<image class="show_box_img" :src="item.url" mode="aspectFill" @click="handlePreview(index)" />
			<uni-icons class="clear_icon" type="clear" size="26" color="#00000080" @click="handleDel(item.name)"></uni-icons>
		</view>
		<view v-if="maxLength > modelValue.length" class="upload_box_item" @click="handleUpload">
			<uni-icons type="plusempty" color="gainsboro" size="60" />
		</view>
	</view>
</template>

<script setup>
	import {
		getUuid
	} from '../../utils/uuid'
	import {
		pathToBase64,
		getLocalFilePath,
	} from '../../uni_modules/sp-html2pdf-render/utils'
	const props = defineProps({
		modelValue: {
			type: Array,
			default: () => [],
		},
		// 最大数量长度
		maxLength: {
			type: [Number, String],
			default: 5,
		},
		// 最大单位（M）
		maxSize: {
			type: [Number, String],
			default: 10,
		},
	})

	const emits = defineEmits(['update:modelValue'])
	// 文件上传
	const handleUpload = () => {
		uni.chooseImage({
			count: props.maxLength - props.modelValue.length,
			success: ({
				tempFiles
			}) => {
				uni.showLoading({
					title: '图片上传中...',
					mask: true
				})
				let newUploadImgs = tempFiles
					.filter((item) => {
						if (props.maxSize * 1024 * 1024 >= item.size) {
							return true
						} else {
							uni.showToast({
								title: `文件超出${props.maxSize}M`,
								icon: 'error',
								duration: 1000,
								mask: true,
							})
						}
					})
					.map((item) => {
						let idx = item.path.lastIndexOf('.')
						let extname = item.path.slice(idx + 1)
						return {
							url: item.path,
							name: getUuid() + '.' + extname,
							extname,
							isNew: true, //是否是新上传的文件
						}
					})
				emits('update:modelValue', props.modelValue.concat(newUploadImgs))
				uni.hideLoading()
			},
			fail: () => {},
		})
	}

	// 文件删除
	const handleDel = (name) => {
		let newUploadImgs = props.modelValue.filter((item) => item.name !== name)
		emits('update:modelValue', newUploadImgs)
	}
	// 文件预览
	const handlePreview = (index) => {
		console.log(props.modelValue.map(item => item.url));
		uni.previewImage({
			current: index,
			urls: props.modelValue.map(item => item.url),
			fail: function(err) {
				console.log(err.errMsg);
			}
		});
	}
</script>

<style lang="scss" scoped>
	.upload_box {
		display: flex;
		flex-wrap: wrap;

		// padding: 20rpx 0;
		&_item {
			margin-right: 16rpx;
			margin-bottom: 20rpx;
			position: relative;
			display: flex;
			justify-content: center;
			align-items: center;
			width: 200rpx;
			height: 200rpx;
			border: 1px solid rgb(210, 210, 210);
			border-radius: 8rpx;

			.clear_icon {
				position: absolute;
				right: -12px;
				top: -12px;
				z-index: 2;
			}
		}

		.show_box {
			&_img {
				width: 100%;
				height: 100%;
			}
		}
	}
</style>